﻿using System;
using System.Web.Mvc;
using Actya.Core.Infrastructure;
using Actya.Core.Security;
using Actya.Core.SiteStructure;

namespace Actya.Web.Filters
{
	public class CmsContextFilter : ActionFilterAttribute
	{
		public override void OnActionExecuting(ActionExecutingContext filterContext)
		{
			// Set CMS context before executing any action.
			var cmsContext = DependencyResolver.Current.GetService<ICmsContext>();
			if (cmsContext.Site == null)
			{
				var siteService = DependencyResolver.Current.GetService<ISiteService>();

				// Site
				cmsContext.Site = siteService.FindSiteByHostUrl(cmsContext.Host.Settings.HostUrl);
			}
			if (cmsContext.User == null && filterContext.HttpContext.User is User)
			{
				cmsContext.User = (User) filterContext.HttpContext.User;
			}
		}
	}
}